package net.xdclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.OssConfig;
import net.xdclass.service.FileService;
import net.xdclass.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class FileServiceImpl  implements FileService {
    @Autowired
    private OssConfig ossConfig;
    @Override
    public String uploadUserUmg(MultipartFile file) {
        //获取相关配置
        String bucketName = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        //创建oss对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取原始文件名  123.jpg
        String originalFilename = file.getOriginalFilename();
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        //拼装Oss上的存储路径 user/2022/11/11/asdas.jpg
        String format = dtf.format(now);
        log.info(format);
        String fileName = CommonUtil.generateUUID();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName="user/"+format+"/"+fileName+extension;
        log.info(newFileName);

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, newFileName, file.getInputStream());
            //拼装返回路径
            if (putObjectResult!=null){
               String url = "https://"+bucketName+"."+endpoint+"/"+newFileName;
               return url;
            }

        } catch (IOException ioException) {
            log.error("文件上传失败{}",ioException);
        }finally {
            //oss关闭 不然造成oss内存泄露
            ossClient.shutdown();
        }
        return null;
    }
}
